package com.service.impl;


import com.domain.DO.FlightClass;
import com.domain.DO.FlightOrder;
import com.domain.DTO.FlightOrderDto;
import com.domain.VO.FlightOrderVo;
import com.domain.assembler.FlightOrderAssembler;
import com.mapper.FlightClassMapper;
import com.mapper.FlightOrderMapper;
import com.service.IFlightOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.domain.factory.FlightOrderFactory.FLIGHT_ORDER_CONVERT;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 大忽悠
 * @since 2022年11月08日
 */
@Service
@RequiredArgsConstructor
public class FlightOrderServiceImpl extends ServiceImpl<FlightOrderMapper, FlightOrder> implements IFlightOrderService {
     private final FlightClassMapper flightClassMapper;
     private final FlightOrderAssembler flightOrderAssembler;

    /**
     * 1.根据买的舱位等级不同,去判断是否还有剩余座位
     * 2.如果用户希望买的座位偏好不存在可用的剩余座位,那么就随机选择一个
     */
    @Transactional
    @Override
    public FlightOrderDto buyFlightTicket(FlightOrderVo flightOrderVo) {
        FlightClass flightClass = flightClassMapper.selectById(flightOrderVo.getFlightClassId());
        flightOrderVo.seatNumberCheck(flightClass);
        Integer seatSeq = flightOrderVo.careUserSeatHobby(flightClass);
        //1.更新当前班次对应的座位信息
        flightClassMapper.updateById(flightClass.updateSeatInfo(seatSeq,flightOrderVo.getDegree()));
        //2.创建订单
        FlightOrder flightOrder = FLIGHT_ORDER_CONVERT.toFlightOrder(flightOrderVo);
        flightOrder.setSeat(seatSeq);
        save(flightOrder);
        //3.返回此次订单详情
        return flightOrderAssembler.createUserOrderInfo(flightClass,flightOrder);
    }
}
